package RabbitMQ.Direct;

import RabbitMQ.Constants.Constants;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeoutException;

public class Producer {
    public static void main(String[] args) throws IOException, TimeoutException {
//        1.建立连接
        ConnectionFactory connectionFactory=new ConnectionFactory();
        connectionFactory.setHost(Constants.HOST);
        connectionFactory.setPort(Constants.PORT);
        connectionFactory.setUsername(Constants.USER_NAME);
        connectionFactory.setPassword(Constants.PASSWORD);
        connectionFactory.setVirtualHost(Constants.VIRTUAL_HOST);
        Connection connection=connectionFactory.newConnection();
//        2.开启信道
        Channel channel=connection.createChannel();
//        3.声明交换机
        channel.exchangeDeclare(Constants.DIRECT_EXCHANGE, BuiltinExchangeType.DIRECT,true);
//        4.声明队列
        channel.queueDeclare(Constants.DIRECT_QUEUE1,true,false,false,null);
        channel.queueDeclare(Constants.DIRECT_QUEUE2,true,false,false,null);
//        5.绑定交换机和队列
        channel.queueBind(Constants.DIRECT_QUEUE1,Constants.DIRECT_EXCHANGE,"a");
        channel.queueBind(Constants.DIRECT_QUEUE2,Constants.DIRECT_EXCHANGE,"a");
        channel.queueBind(Constants.DIRECT_QUEUE2,Constants.DIRECT_EXCHANGE,"b");
        channel.queueBind(Constants.DIRECT_QUEUE2,Constants.DIRECT_EXCHANGE,"c");
//        6.发送消息
        String msg1="my routingKey is a";
        channel.basicPublish(Constants.DIRECT_EXCHANGE,"a",null,msg1.getBytes(StandardCharsets.UTF_8));
        String msg2="my routingKey is b";
        channel.basicPublish(Constants.DIRECT_EXCHANGE,"b",null,msg2.getBytes(StandardCharsets.UTF_8));
        String msg3="my routingKey is c";
        channel.basicPublish(Constants.DIRECT_EXCHANGE,"c",null,msg3.getBytes(StandardCharsets.UTF_8));
        channel.close();
        connection.close();
    }
}
